package httputil

import (
	"fmt"
	"net"
	"strings"
)

const (
	// Ipv4_host_template Ipv4的host模板
	Ipv4_host_template = "%s:%s"
	// Ipv6_host_template Ipv4的host模板
	Ipv6_host_template = "[%s]:%s"
)

// GetIpAndPortFromHost 从一个包含了ip和端口的host中解析出ip和端口(没有端口的也可以解析，返回的端口为0)
func GetIpAndPortFromHost(host string) (string, string, error) {
	host, port, err := parseHostPort(host)
	if err != nil {
		return "", "", err
	}
	return host, port, nil
}

// FormatHostWithIpAndPort 根据指定的ip和端口，格式化一个host(包含了ipv4和ipv6的类型)
func FormatHostWithIpAndPort(ip, port string) (string, error) {
	// 如果是ipv6包含了方括号，把方括号去掉
	if strings.HasPrefix(ip, "[") && strings.HasSuffix(ip, "]") {
		ip = ip[1 : len(ip)-1]
	}
	ipNet := net.ParseIP(ip)
	if ipNet == nil {
		return "", fmt.Errorf("invalid IP address")
	}
	if ipNet.To4() != nil {
		return fmt.Sprintf(Ipv4_host_template, ip, port), nil
	}
	if ipNet.To16() != nil {
		return fmt.Sprintf(Ipv6_host_template, ip, port), nil
	}
	return "", fmt.Errorf("unsupported IP type")
}

func parseHostPort(hostPort string) (string, string, error) {
	host, port, err := net.SplitHostPort(hostPort)
	if err != nil {
		// 直接解析IP地址
		if strings.HasPrefix(hostPort, "[") && strings.HasSuffix(hostPort, "]") {
			return hostPort[1 : len(hostPort)-1], "0", nil
		}
		return hostPort, "0", nil
	}
	return host, port, nil
}

func GetIPType(host string) (string, error) {
	ip := net.ParseIP(host)
	if ip == nil {
		return "", fmt.Errorf("invalid IP address")
	}
	if ip.To4() != nil {
		return "IPv4", nil
	}
	if ip.To16() != nil {
		return "IPv6", nil
	}
	return "", fmt.Errorf("unsupported IP type")
}
